package models

import (
	"gorm.io/gorm"
	"week2/types"
)

type Spike struct {
	gorm.Model
	UserId    int     `json:"userId" form:"userId" gorm:"column:user_id;comment:用户id;size:10;"`           //用户id
	ShopId    int     `json:"shopId" form:"shopId" gorm:"column:shop_id;comment:商品id;size:10;"`           //商品id
	Gotime    string  `json:"gotime" form:"gotime" gorm:"column:gotime;comment:开始时间;"`                    //开始时间
	Stoptime  string  `json:"stoptime" form:"stoptime" gorm:"column:stoptime;comment:结束时间;"`              //结束时间
	ShopNum   int     `json:"shopNum" form:"shopNum" gorm:"column:shop_num;comment:商品数量;size:10;"`        //商品数量
	ShopPrice float64 `json:"shopPrice" form:"shopPrice" gorm:"column:shop_price;comment:商品单价;size:10;"`  //商品单价
	ShopMeny  int     `json:"shopMeny" form:"shopMeny" gorm:"column:shop_meny;comment:商品总价格;size:10;"`    //商品总价格
	ShopCount int     `json:"shopCount" form:"shopCount" gorm:"column:shop_count;comment:商品总数量;size:10;"` //商品总数量
}

type SpikeService struct{}

// CreateSpike 创建spike表记录
// Author [yourname](https://github.com/yourname)
func (s *Spike) CreateSpike() error {
	err := types.Db.Create(&s).Error
	return err
}

// DeleteSpike 删除spike表记录
// Author [yourname](https://github.com/yourname)
func (spikeService *SpikeService) DeleteSpike(id string) (err error) {
	err = types.Db.Delete(Spike{}, "id = ?", id).Error
	return err
}

// DeleteSpikeByIds 批量删除spike表记录
// Author [yourname](https://github.com/yourname)
func (spikeService *SpikeService) DeleteSpikeByIds(ids []string) (err error) {
	err = types.Db.Delete(Spike{}, "id in ?", ids).Error
	return err
}

// UpdateSpike 更新spike表记录
// Author [yourname](https://github.com/yourname)
func (spikeService *SpikeService) UpdateSpike(spike *Spike) (err error) {
	err = types.Db.Model(Spike{}).Where("id = ?", spike.ID).Updates(&spike).Error
	return err
}

// GetSpike 根据id获取spike表记录
// Author [yourname](https://github.com/yourname)
func (spikeService *SpikeService) GetSpike(id string) (spike Spike, err error) {
	err = types.Db.Where("id = ?", id).First(&spike).Error
	return
}

// GetSpikeInfoList 分页获取spike表记录
// Author [yourname](https://github.com/yourname)
func (spikeService *SpikeService) GetSpikeInfoList(PageSize, Page int) (list []Spike, total int64, err error) {
	limit := PageSize
	offset := PageSize * (Page - 1)
	// 创建db
	db := types.Db.Model(&Spike{})
	var spikes []Spike
	// 如果有条件搜索 下方会自动创建搜索语句
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&spikes).Error
	return spikes, total, err
}
